library(shiny)
library(tidyverse)

# Load precomputed data
sct_data <- readRDS(file = "data/rds/sct_data.rds")
choropleth_data <- readRDS(file = "data/rds/choropleth_data.rds")
parallelcoordinates_data <- readRDS(file = "data/rds/parallelcoordinates_data.rds")
bar_data  <- readRDS(file = "data/rds/bar_data.rds")
radar_data  <- readRDS(file = "data/rds/radar_data.rds")
treemap_data <- readRDS(file = "data/rds/treemap_data.rds")
tree_data <- readRDS(file = "data/rds/tree_data.rds")

heatmap_data_csv_2012<- read_csv2(file = "data/heatmap/br_mes_dia_2012.csv", na = "NA")
heatmap_data_csv_2013<- read_csv2(file = "data/heatmap/br_mes_dia_2013.csv", na = "NA")
heatmap_data_csv_2014<- read_csv2(file = "data/heatmap/br_mes_dia_2014.csv", na = "NA")
heatmap_data_csv_2015<- read_csv2(file = "data/heatmap/br_mes_dia_2015.csv", na = "NA")
heatmap_data_csv_2016<- read_csv2(file = "data/heatmap/br_mes_dia_2016.csv", na = "NA")
heatmap_data_csv_2017<- read_csv2(file = "data/heatmap/br_mes_dia_2017.csv", na = "NA")

make_list <- function(x) {
    apply(x, 1, function(y) {
        list(month = as.integer(y[1]),
             day = as.integer(y[2]),
             value = as.integer(y[3]))
    })
    
}

heatmap_2012_data <- make_list(heatmap_data_csv_2012)
heatmap_2013_data <- make_list(heatmap_data_csv_2013)
heatmap_2014_data <- make_list(heatmap_data_csv_2014)
heatmap_2015_data <- make_list(heatmap_data_csv_2015)
heatmap_2016_data <- make_list(heatmap_data_csv_2016)
heatmap_2017_data <- make_list(heatmap_data_csv_2017)


server <- function(input, output, session) {

    observe({

        session$sendCustomMessage(type="scatterplot_values", message = sct_data)

    })

    observe({

        session$sendCustomMessage(type="dendrogram_values",
                                  message = list(tree_data,
                                                 bar_data,
                                                 radar_data))

    })

    observe({

        session$sendCustomMessage(type="treemap2_values", message = treemap_data)

    })


    observe({

        session$sendCustomMessage(type="choropleth_values", message = choropleth_data)

    })

    observe({

        session$sendCustomMessage(type="parallelcoordinates_values", message = parallelcoordinates_data)

    })

    observe({

        session$sendCustomMessage(type="heatmap_values", message = list(heatmap_2012_data,
                                                                        heatmap_2013_data,
                                                                        heatmap_2014_data,
                                                                        heatmap_2015_data,
                                                                        heatmap_2016_data,
                                                                        heatmap_2017_data))

    })

}
